import requests
import json
import os
from urllib.parse import urlparse
import time
import re

# 配置参数
SEARCH_KEYWORD = "小升初  群"
DOWNLOAD_FOLDER = "小红书图片"
COOKIE = 'abRequestId=fbfa7d02-66a0-5204-94e6-c5a5c216450f; webBuild=4.72.0; a1=197f2237526tbv6jk0lf8nx5v84yp8a9byl377ils50000392550; webId=f70b09d0196910c9aa5b7071511e4dd8; _qimei_uuid42=1970a0a15271009bcaf8a3547c68aa47461ca4dc1b; _qimei_i_3=23d22cd0c30b5989c4c3ff315ad67bb4a6efacf4135c0786e78b285b7293226932633f943c89e295d1a8; _qimei_h38=; gid=yjWiJJqYWyDYyjWiJJqW2vW3JK9DhKVT81iY11MIC2hY4q28vUY0jW888qjJ2288KWSJj2j4; xsecappid=xhs-pc-web; _qimei_fingerprint=5b3d1614be9a1d1c8a8b6843a96d226e; web_session=0400698f4f3c6656dcbffd665a3a4bcc343400; websectiga=cf46039d1971c7b9a650d87269f31ac8fe3bf71d61ebf9d9a0a87efb414b816c; sec_poison_id=165ed7f9-3283-4a92-9d9c-9857880d0d59; acw_tc=0ad5976717521282411112695e8ddbf7a4e683b1bd2b161e5c3a14320e44e5; loadts=1752128244291; _qimei_i_1=52c45ddbfd52; unread={%22ub%22:%22684d8ba60000000023015ae8%22%2C%22ue%22:%22686c7ff9000000001203e6e6%22%2C%22uc%22:26}'

def clean_filename(filename):
    """清理文件名中的非法字符"""
    # 移除或替换非法字符
    filename = re.sub(r'[<>:"/\\|?*]', '', filename)
    # 替换空格为下划线
    filename = filename.replace(' ', '_')
    # 限制长度
    return filename[:50] if len(filename) > 50 else filename

def download_image(url, folder_path, filename):
    """下载图片到指定文件夹"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        
        # 确保文件夹存在
        os.makedirs(folder_path, exist_ok=True)
        
        # 保存图片
        file_path = os.path.join(folder_path, filename)
        with open(file_path, 'wb') as f:
            f.write(response.content)
        
        print(f"图片已保存: {file_path}")
        return True
    except Exception as e:
        print(f"下载图片失败 {url}: {e}")
        return False

def search_xiaohongshu_notes():
    """搜索小红书笔记并下载图片"""
    
    # 请求URL
    url = "https://edith.xiaohongshu.com/api/sns/web/v1/search/notes"
    
    # 请求头
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Cookie': COOKIE
    }
    
    # 创建保存图片的文件夹
    os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)
    
    # 循环获取前5页数据
    for page in range(1, 6):
        print(f"\n=== 正在获取第 {page} 页数据 ===")
        
        # 请求数据
        data = {
            "keyword": SEARCH_KEYWORD,
            "page": page,
            "page_size": 20,
            "search_id": "2f1jxbw64741b4jcumh46@2f1jxdfpmnba1p9b81p88",
            "sort": "general",
            "note_type": 0,
            "ext_flags": [],
            "filters": [
                {
                    "tags": [
                        "time_descending"
                    ],
                    "type": "sort_type"
                },
                {
                    "tags": [
                        "不限"
                    ],
                    "type": "filter_note_type"
                },
                {
                    "tags": [
                        "不限"
                    ],
                    "type": "filter_note_time"
                },
                {
                    "tags": [
                        "不限"
                    ],
                    "type": "filter_note_range"
                },
                {
                    "tags": [
                        "不限"
                    ],
                    "type": "filter_pos_distance"
                }
            ],
            "geo": "",
            "image_formats": [
                "jpg",
                "webp",
                "avif"
            ]
        }
        
        # 发送POST请求
        try:
            response = requests.post(url, headers=headers, json=data, timeout=30)
            response.raise_for_status()
            
            # 解析响应
            result = response.json()
            
            # 检查响应状态
            if result.get('code') == 0 and result.get('success'):
                print(f"第 {page} 页请求成功！")
                
                # 获取笔记数据
                items = result.get('data', {}).get('items', [])
                print(f"获取到 {len(items)} 条笔记")
                
                # 遍历每个笔记
                for i, item in enumerate(items):
                    if item.get('model_type') == 'note':
                        note_card = item.get('note_card', {})
                        title = note_card.get('display_title', f'note_{i}')
                        image_list = note_card.get('image_list', [])
                        
                        print(f"\n处理笔记: {title}")
                        print(f"图片数量: {len(image_list)}")
                        
                        # 清理标题作为文件名
                        clean_title = clean_filename(title)
                        
                        # 为每个笔记创建子文件夹
                        note_folder = os.path.join(DOWNLOAD_FOLDER, f"note_{(page-1)*20+i+1}_{clean_title}")
                        
                        # 下载图片
                        image_count = 0
                        for j, image_info in enumerate(image_list):
                            info_list = image_info.get('info_list', [])
                            for k, info in enumerate(info_list):
                                image_url = info.get('url', '')
                                if image_url:
                                    image_count += 1
                                    
                                    # 根据URL判断文件类型
                                    if 'webp' in image_url:
                                        ext = '.webp'
                                    elif 'jpg' in image_url or 'jpeg' in image_url:
                                        ext = '.jpg'
                                    elif 'png' in image_url:
                                        ext = '.png'
                                    else:
                                        ext = '.jpg'  # 默认jpg
                                    
                                    # 使用标题作为文件名，多张图片加后缀
                                    if image_count == 1:
                                        filename = f"{clean_title}{ext}"
                                    else:
                                        filename = f"{clean_title}_{image_count}{ext}"
                                    
                                    print(f"下载图片: {filename}")
                                    download_image(image_url, note_folder, filename)
                                    
                                    # 添加延迟避免请求过快
                                    time.sleep(0.5)
            else:
                print(f"第 {page} 页请求失败: {result}")
                
        except requests.exceptions.RequestException as e:
            print(f"第 {page} 页请求异常: {e}")
        except json.JSONDecodeError as e:
            print(f"第 {page} 页JSON解析错误: {e}")
        except Exception as e:
            print(f"第 {page} 页其他错误: {e}")
        
        # 页面间添加延迟
        if page < 5:
            print(f"等待 2 秒后获取下一页...")
            time.sleep(2)

if __name__ == "__main__":
    print("开始搜索小红书笔记并下载图片...")
    search_xiaohongshu_notes()
    print("任务完成！") 